//
//  ArrayTest.m
//  MacTestProject
//
//  Created by LiuLichen on 2022/4/11.
//

#import "ArrayTest.h"

@implementation ArrayTest

- (id) init {
    self = [super init];

    [self testInit];
    [self testOperation];

    return self;
}

- (void) testInit {
    NSArray* arr0 = @[@"jack", @"dave"];
    NSArray* arr1 = [NSArray array];
    NSArray* arr2 = [NSArray arrayWithObjects: @"jack", @"rose", nil];
    NSLog(@"%@", arr0);
    NSLog(@"%@", arr1);
    NSLog(@"%@", arr2);
    /**
     id obj1 = ...;
     id obj2 = nil;
     id obj3 = ...;
     // arrarWithObjects will process each parameter in turn until find nil, so arrA only contains obj1.
     NSArray* arrA = [NSArray arrarWithObjects: obj1, obj2, obj3, nil];
     // An exception will be thrown when creating arrB.
     NSArray* arrB = @[obj1, obj2, obj3];
     */
    NSMutableArray* mArr = [@[@1, @2, @3]mutableCopy];
    NSLog(@"%@", mArr);
}

- (void) testOperation {
    {
        NSArray* arr = @[@"jack", @"rose", @"lili"];
        NSLog(@"The count of arr is %lu", [arr count]);
        for (int i = 0; i < [arr count]; i++) {
            NSLog(@"The object at %d is %@, also can get %@ by []", i, [arr objectAtIndex: i], arr[i]);
        }
    }
    {
        NSMutableArray* arr = [NSMutableArray arrayWithCapacity: 4];
        [arr addObject: @".net"];
        [arr addObject: @"java"];
        [arr addObject: @"c++"];
        [arr addObject: @"javascript"];
        [arr addObject: [[NSObject alloc]init]];
        for (NSObject* obj in arr) {
            NSLog(@"initialize, obj %@", obj);
        }
        [arr removeObjectAtIndex: 1];
        for (NSObject* obj in arr) {
            NSLog(@"after removing, obj %@", obj);
        }
        [arr insertObject: @"inserted" atIndex: 1];
        for (NSObject* obj in arr) {
            NSLog(@"after inserting, obj %@", obj);
        }
        [arr replaceObjectAtIndex: 1 withObject: @"replaced"];
        for (NSObject* obj in arr) {
            NSLog(@"after replacing, obj %@", obj);
        }
    }
    {
        NSString* (^commaSeparatedStringFromObject)(NSArray*) = ^(NSArray* array) {
            NSMutableString* ms = [NSMutableString new];
            for (id obj in array) {
                if ([obj isKindOfClass:[NSString class]]) {
                    [ms appendFormat: @"%@", obj];
                } else if ([obj isKindOfClass:[NSNumber class]]) {
                    [ms appendFormat: @"%d", [obj intValue]];
                } else {
                    // Type not supported
                }
            }
            return ms;
        };
        NSArray* arr = @[@"ss", @12, @[@3.5, @6], @{@"name": @"dict"}];
        NSString* str = commaSeparatedStringFromObject(arr);
        NSLog(@"%@", str);          // ss12
    }
}

@end
